/*
 * @Description: 用户群聊表
 * @Author: fhw
 * @Date: 2022-11-18 11:13:34
 */
import { Controller, Get, Post, Body, Patch, Param, Delete, Query, UseFilters, HttpCode, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiBody, ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
import { equals, isNil } from 'ramda';
import { ChatUserService } from 'src/chat_user/chat_user.service';
import { ChatUser } from 'src/chat_user/entities/chat_user.entity';
import { GroupChat } from 'src/group-chat/entities/group-chat.entity';
import { GroupChatService } from 'src/group-chat/group-chat.service';
import { HttpExceptionFilter } from 'src/http-exception.filter';
import { SysMessageService } from 'src/sys_message/sys_message.service';
import { throwHttp } from 'src/utlis';
import { CreateChatUserGroupParams } from './chat_user_group.module';
import { ChatUserGroupService } from './chat_user_group.service';
import { ApplyAddChatUserGroupDto, ChatUserGroupPageDto, InviteAddChatUserGroupDto, UpdateChatUserGroupDto } from './dto/chat_user_group.dto';
import { ChatUserGroupResult } from './entities/chat_user_group.entity';
import { AuthGuard } from '@nestjs/passport';
@ApiBearerAuth() // swagger文档设置token
@ApiTags('用户群聊表')
@Controller('chat-user-group')
export class ChatUserGroupController {
  constructor(
    private readonly chatUserGroupService: ChatUserGroupService,
    private readonly chatUserService: ChatUserService,
    private readonly groupChatService: GroupChatService,
    // 系统消息
    private readonly sysMessageService: SysMessageService
  ) { }

  @Get('/chatUserGroupPage')
  @ApiResponse({
    status: 200,
    description: '用户群聊表列表',
    type: ChatUserGroupResult,
  })
  @ApiOperation({ summary: '用户群聊表列表', operationId: 'chatUserGroupPage'  })  
  @UseFilters(new HttpExceptionFilter())
  @UseGuards(AuthGuard('jwt'))//jwt策略，身份鉴权
  getChatUserGroupPage(@Query() params: ChatUserGroupPageDto) {
    return this.chatUserGroupService.getChatUserGroupPage(params);
  }
  // 创建用户群聊
  @UseFilters(new HttpExceptionFilter())
  @UseGuards(AuthGuard('jwt'))//jwt策略，身份鉴权
  async createChatUserGroup(@Query() params: CreateChatUserGroupParams | CreateChatUserGroupParams[], { groupChat }) {
    // 判断传入用户是否存在
    if (params instanceof Array) {
      const paramsList = await Promise.all(params.map(async item => {
        const chatUser = await this.chatUserService.getUserInfo({ id: item.userId })
        return {
          ...item,
          chatUser
        }
      }))
      return await this.chatUserGroupService.createChatUserGroup(paramsList, { groupChat } as { chatUser: ChatUser; groupChat: GroupChat });
    } else {
      return await this.chatUserGroupService.createChatUserGroup([params], { groupChat } as { chatUser: ChatUser; groupChat: GroupChat });
    }
  }
  // 更新用户群聊信息
  @HttpCode(200)
  @Post('/adoptApply')
  @ApiQuery({
    description: '通过申请加入群聊',
    type: UpdateChatUserGroupDto,
  })
  @ApiBody({ description: '通过申请加入群聊', type: UpdateChatUserGroupDto })
  @ApiOperation({ summary: '通过申请加入群聊', operationId: 'adoptApply'  })
  @UseFilters(new HttpExceptionFilter())
  @UseGuards(AuthGuard('jwt'))//jwt策略，身份鉴权
  async adoptApply(@Query() params: UpdateChatUserGroupDto) {
    // 判断传入用户是否存在
    await this.chatUserService.getUserInfo({ id: params.userId })
    return this.chatUserGroupService.updateChatUserGroup(params);
  }

  @UseFilters(new HttpExceptionFilter())
  deleteChatUserGroup(@Query() params: UpdateChatUserGroupDto) {
    return this.chatUserGroupService.deleteChatUserGroup(params);
  }

  @HttpCode(200)
  @Post('/inviteAddChatUserGroup')
  @ApiQuery({
    description: '邀请加入群聊',
    type: InviteAddChatUserGroupDto,
  })
  @ApiBody({ description: '邀请加入群聊', type: InviteAddChatUserGroupDto })
  @ApiOperation({ summary: '邀请加入群聊', operationId: 'inviteAddChatUserGroup'  })
  @UseFilters(new HttpExceptionFilter())
  @UseGuards(AuthGuard('jwt'))//jwt策略，身份鉴权
  async inviteAddChatUserGroup(@Body() body: InviteAddChatUserGroupDto) {
    try {
      const { userId, inviterId, group_id } = body
      if (userId === inviterId) {
        throwHttp('邀请失败：无法邀请自己加入群聊')
      }
      await this.chatUserService.getUserInfo({ id: inviterId })
      const chatUser = await this.chatUserService.getUserInfo({ id: userId })
      const groupChat = await this.groupChatService.getGroupChatInfo({ group_id })
      if (groupChat.managerId === inviterId) {
        throwHttp('邀请失败：被邀请人为群主')
      }
      const isComplete = await this.chatUserGroupService.inviteAddChatUserGroup(body, { chatUser, groupChat })
      if (!isComplete) {
        throwHttp('邀请失败')
      }
      // 消息通知
      const params = {
        message_title: '邀请加入群聊',
        message_content: `${chatUser.username}邀请你加入${groupChat.groupChatName}群聊`,
        message_type: 2,
        created: chatUser,
        toUserId: inviterId,
        createdId: userId,
        status: 0,
        message_status: 0,
        userId: chatUser.id as number
      }
      await this.sysMessageService.createSysMessage(params)
      return '邀请成功'
    } catch (error) {
      throwHttp(error.message)
    }
  }

  @HttpCode(200)
  @Post('/applyAddChatUserGroup')
  @ApiQuery({
    description: '申请加入群聊',
    type: ApplyAddChatUserGroupDto,
  })
  @ApiBody({ description: '申请加入群聊', type: ApplyAddChatUserGroupDto })
  @ApiOperation({ summary: '申请加入群聊', operationId: 'applyAddChatUserGroup'  })
  @UseFilters(new HttpExceptionFilter())
  @UseGuards(AuthGuard('jwt'))//jwt策略，身份鉴权
  async applyAddChatUserGroup(@Body() body: ApplyAddChatUserGroupDto) {
    try {
      // 判断是否加入成功
      let isComplete: boolean = false
      const { userId, group_id, content } = body
      const chatUser = await this.chatUserService.getUserInfo({ id: userId })
      const chatUserGroupInfo = await this.chatUserGroupService.getChatUserGroupInfo({ userId, group_id })
      const groupChat = await this.groupChatService.getGroupChatInfo({ group_id })
      if (!isNil(chatUserGroupInfo) && chatUserGroupInfo.is_join === 1) {
        throwHttp('您已在当前群聊，无需加入')
      }
      if (!isNil(chatUserGroupInfo) && chatUserGroupInfo.is_join === 0) {
        throwHttp('您已被邀请加入群聊，请到通知栏通过邀请')
      }
      if (!isNil(chatUserGroupInfo) && chatUserGroupInfo.is_join === 3) {
        throwHttp('您已申请加入群聊，等待管理员审核')
      }
      // 查无信息则手动创建
      if (isNil(chatUserGroupInfo)) {
        const data = await this.chatUserGroupService.createChatUserGroup([{
          userId,
          group_id,
          chatUser,
          is_join: 3
        }], { groupChat })
        if (data) {
          isComplete = true
        }
      } else {
        const { affected } = await this.chatUserGroupService.updateChatUserGroup({
          userId, group_id, is_join: 3,
        })
        if (affected) {
          isComplete = true
        }
      }
      if (!isComplete) {
        throwHttp('加入群聊失败，请联系管理员处理')
        return
      }
      // 消息通知
      const params = {
        message_title: `${chatUser.username}申请加入${groupChat.groupChatName}群聊`,
        message_content: `验证消息：${content}`,
        message_type: 2,
        created: chatUser,
        toUserId: groupChat.managerId,
        createdId: userId,
        status: 0,
        message_status: 0,
        userId: chatUser.id as number
      }
      await this.sysMessageService.createSysMessage(params)
      return '申请加入群聊成功，等待管理员审核'
    } catch (error) {
      throwHttp(error.message)
    }
  }
  @HttpCode(200)
  @Post('/quitGroupChat')
  @ApiQuery({
    description: '退出群聊',
    type: UpdateChatUserGroupDto,
  })
  @ApiBody({ description: '退出群聊', type: UpdateChatUserGroupDto })
  @ApiOperation({ summary: '退出群聊', operationId: 'quitGroupChat'  })
  @UseFilters(new HttpExceptionFilter())
  @UseGuards(AuthGuard('jwt'))//jwt策略，身份鉴权
  async quitGroupChat(@Body() body: UpdateChatUserGroupDto) {
    try {
      const { userId, group_id, is_join } = body
      const chatUser = await this.chatUserService.getUserInfo({ id: userId })
      // 查询用户群聊
      const chatUserGroupInfo = await this.chatUserGroupService.getChatUserGroupInfo({ userId, group_id })
      const groupChat = await this.groupChatService.getGroupChatInfo({ group_id })
      if (isNil(chatUserGroupInfo)) {
        throwHttp('您未加入该群聊')
      }
      if (equals(userId, groupChat.managerId)) {
        throwHttp('您是当前群聊管理者，无法退出，如需退出，请解散群聊')
      }
      await this.chatUserGroupService.deleteChatUserGroup({ userId, group_id })
      const params = {
        message_title: `退出群聊`,
        message_content: `${chatUser.username}退出群聊`,
        message_type: 2,
        created: chatUser,
        toUserId: groupChat.managerId,
        createdId: userId,
        status: 0,
        message_status: 0,
        userId: chatUser.id as number
      }
      await this.sysMessageService.createSysMessage(params)
      return '退出成功'
    } catch (error) {
      throwHttp(error.message)
    }
  }
}
